//
//  RootViewController.m
//  GameDemo
//
//  Created by deepak kumar on 04/04/10.
//  Copyright home 2010. All rights reserved.
//

#import "RootViewController.h"
#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>

#define UPDATE_DT		(1.0f/60.0f)

const float CELL_WIDTH = 60;
const float CELL_HEIGTH = 42.5;

const float CELL_3D_WIDTH = 256.0/8.0;
const float CELL_3D_HEIGTH = 256.0/7.0;

int MOVE_STEPS_COUNT = 0;

@interface RootViewController(Draw)

-(void) drawCharacterAtCol:(int)n Row:(int)i;

-(void) startOGLTimer;
-(void) stopOGLTimer;

@end

@implementation RootViewController
@synthesize oglBoardView;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
	
	board = [[NSMutableArray alloc] initWithCapacity:0];
	boardSprite = [[Sprite alloc] initWithFileNamed:@"BWBoard256.png"];
	
	bgSprite = [[Sprite alloc] initWithFileNamed:@"background_board.jpg"];
	[bgSprite setTextCoordPixelsLeftTop:Vector3Make(0, 0, 0) RightBottom:Vector3Make(480.0, 320, 0)];
	bgSprite.size = Vector3Make(320, 480, 0);
	bgSprite.pos = Vector3Make(0, 0, 0);
	
	explotionPreloadSprite = [BoardCharSprite alloc];
	[explotionPreloadSprite initWithFileName:@"Explotion_3D.png" FramesCount:16 FramesPerLine:7];
	
	[self startOGLTimer];
	
	[self createBoard];
//	[self paintBoard];
	
    //[super viewDidLoad];
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

#pragma mark GameTimer 
-(void) startOGLTimer
{
	[self stopOGLTimer];
	
	oglBoardUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:/*UPDATE_DT*/ 0.05 target:self selector:@selector(paintOGLBoard) userInfo:nil repeats:YES];
	[oglBoardUpdateTimer  retain];
}

-(void) stopOGLTimer
{
	[oglBoardUpdateTimer invalidate];
	[oglBoardUpdateTimer release];
	
	oglBoardUpdateTimer = nil;
}

#pragma mark paintOGLBoard

-(void) paintBG
{
	Renderer *renderer = oglBoardView.renderer;
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrthof(0, renderer.backingWidth, 0, renderer.backingHeight, -10, 10);
	
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	glTranslatef(0,bgSprite.size.y, 0);
	glRotatef(180, 1, 0, 0);
	
	bgSprite.pos = Vector3Make(0, 0, 0);
	
	glDisable(GL_DEPTH_TEST);
	
	[renderer drawRendereble:bgSprite];
	[renderer drawRenderebleObjects];
	
	glEnable(GL_DEPTH_TEST);
	
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	//goto endRender;
	
	glMatrixMode(GL_MODELVIEW);
}


- (void) paintOGLBoard
{
	//NSLog(@"paintOGLBoard");
	Renderer *renderer = oglBoardView.renderer;
	
	[renderer setClearColor:ColorRGBAMake(0.6, 0.6, 0, 1)];
	[renderer drawBegin];
	
	[renderer disableShading];
	[renderer disableFaceCulling];
	[renderer enableTextures];
	
	[self paintBG];
	
	glDepthMask(GL_TRUE);
	
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER,0.1f);
	glEnable(GL_DEPTH_TEST);
	
	
	
	boardSprite.pos = *vecZero;
	[renderer drawRendereble:boardSprite];
	[renderer drawRenderebleObjects];
	glDisable(GL_DEPTH_TEST);
	
	/*
	 *	Draw colored squares - good,evil,hightlight
	 */
	//for (int i = 0; i < 7; i++) {		
	NSLog(@"Chactor:%d",[board count]);
		for (int n = 0; n < [board count]; n++) 
		{	
			Cell *cell = [board objectAtIndex:n];
			
			Vector3 cellPos = Vector3Make(n*CELL_3D_WIDTH, 2*n*CELL_3D_HEIGTH, -0.01f);
			
			if (cell.character != nil) 
			{			
//				if (cell.character.good == goodTurn && !animating) {

				if (cell.character.good) 
					{
						goodSquareSprite.pos = cellPos;
						[renderer drawRendereble:goodSquareSprite];
						[renderer drawRenderebleObjects];
					} 
					else 
					{
						evilSquareSprite.pos = cellPos;
						[renderer drawRendereble:evilSquareSprite];
						[renderer drawRenderebleObjects];
					}
				//}
			}
			
			if (cell.canMove) 
			{
				highlightSquareSprite.pos = cellPos;
				[renderer drawRendereble:highlightSquareSprite];
				[renderer drawRenderebleObjects];
			}
		}
///	}
	
	[renderer drawRenderebleObjects];
	
	/*
	 *	Draw characters
	 */
	
	Vector3 cameraRelBardCenterPos;
	Vector3 boardCenter = Vector3Make(128.0f,128.0f,0.0f);
	Vector3 cameraPos = oglBoardView.camera.pos;
	
	vec3Sub(&cameraPos,&boardCenter,&cameraRelBardCenterPos);
	
	float boardK = boardCenter.x/boardCenter.y;
	//float boardK = 1.0f;
	float k = 0;
	
	k = cameraRelBardCenterPos.x!=0 ? fabs(cameraRelBardCenterPos.y/cameraRelBardCenterPos.x) : 99999;
	
	int x = cameraRelBardCenterPos.x;
	int y = cameraRelBardCenterPos.y;
	
		
			for (int n = 0; n < 2; n++) 
			{	
				[self drawCharacterAtCol:n Row:2*n];
			}

	
	//	boardSprite.pos = *vecZero;
	//	[renderer drawRendereble:boardSprite];
	//	[renderer drawRenderebleObjects];
	
	[renderer drawEnd];	
}



#pragma mark createBoard
- (void)createBoard {
	
	[board removeAllObjects];
	
	//for (int i = 0; i < 7; i++) {
		
		for (int n = 0; n < 2; n++) {
			Cell *cell = [[Cell alloc] init];
			
						
			if (n==0) {
				Character *character = [[Character alloc] initWithName:@"Warrior" isGood:NO];
				character.health = 20.0;
				character.currentHealth = 20.0;
				character.speed = 4.0;
				character.damage = 4.0;
				character.weaponSpeed = 5.0;
				character.score = 30;
				
				cell.character = character;
				[character release];
			}
			
			if (n==1) {
				Character *character = [[Character alloc] initWithName:@"Ghoul" isGood:NO];
				character.health = 25.0;
				character.currentHealth = 25.0;
				character.speed = 5.5;
				character.damage = 5.5;
				character.weaponSpeed = 6.0;
				character.score = 40;
				
				cell.character = character;
				[character release];
			}
			[board addObject:cell];
			[cell release];
		}
}
	
	// adjust the AI for the Level (easy, medium, hard) of the game
	// also adjust for the number of refreshes... by adding two to these numbers

	//}
//}



-(void) drawCharacterAtCol:(int)n Row:(int)i
{
	Renderer *renderer = oglBoardView.renderer;
	
	Cell *cell = [board objectAtIndex:n];
	
	if(cell.character)
	{
		CGPoint charPos = CGPointMake(n * CELL_3D_WIDTH, i * CELL_3D_HEIGTH);
		
		static float t = 0;
		t += UPDATE_DT;
		
		[cell.character.sprite updateWithTime:t DeltaTime:UPDATE_DT];
		cell.character.sprite.cameraPos = oglBoardView.camera.pos;
		
//		if(cell.character!=animatedCharacter){
			// Correct line
			cell.character.sprite.pos = Vector3Make(charPos.x, charPos.y, -0.02f); 
			
			//cell.character.sprite.pos = Vector3Make(128, 128, -0.01);
			//cell.character.sprite.pos = planePoint;
//		}
		
		[renderer drawRendereble:cell.character.sprite];
	}
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[explotionPreloadSprite release];
	[oglBoardView release];
    [super dealloc];
}


@end

